from conan import ConanFile
from conan.tools.apple import fix_apple_shared_install_name
from conan.tools.build import cross_building
from conan.tools.env import VirtualBuildEnv
from conan.tools.gnu import PkgConfigDeps
from conan.tools.files import (
    apply_conandata_patches,
    copy,
    export_conandata_patches,
    get,
    rename,
    rm,
    rmdir
)
from conan.tools.gnu import Autotools, AutotoolsToolchain
from conan.tools.layout import basic_layout
from conan.tools.microsoft import is_msvc, unix_path
from conan.tools.scm import Version
import os
import subprocess
from pathlib import Path

required_conan_version = ">=1.54.0"


class LibstropheConan(ConanFile):
    name = "spidermonkey"
    description = "SpiderMonkey is Mozilla's JavaScript engine."
    license = ("Mozilla ")
    url = "https://github.com/conan-io/conan-center-index"
    homepage = "https://github.com/ricardoquesada/Spidermonkey"
    topics = ("JavaScript", "engine")

    package_type = "library"
    settings = "os", "arch", "compiler", "build_type"
    options = {
        "shared": [True, False],
        "fPIC": [True, False],
    }
    default_options = {
        "shared": False,
        "fPIC": True,
    }

    @property
    def _settings_build(self):
        return getattr(self, "settings_build", self.settings)

    def config_options(self):
        if self.settings.os == "Windows":
            del self.options.fPIC

    def configure(self):
        if self.options.shared:
            self.options.rm_safe("fPIC")
        
    def build_requirements(self):
        if self._settings_build.os == "Windows":
            if not self.conf.get("tools.microsoft.bash:path", check_type=str):
                self.tool_requires("msys2/cci.latest")
            self.win_bash = True
    def layout(self):
        basic_layout(self)
        
    def source(self):
        get(self, **self.conan_data["sources"][self.version], strip_root=True)

    def generate(self):
        env = VirtualBuildEnv(self)
        env.generate()

        tc = AutotoolsToolchain(self)
        tc.generate()

    def chmod_file(self):
        chmod_cmd = ['chmod', '-R', '777']
        chmod_cmd.append(os.path.join(self.source_folder, "js/src/configure"))
        subprocess.run(chmod_cmd, stdout=subprocess.PIPE)
        
    def build(self):
        if self._settings_build.os == "Linux":
            self.chmod_file()
        apply_conandata_patches(self)
        autotools = Autotools(self)
        # only support ohos
        sdk_path = os.environ.get('OHOS_SDK').replace("\\", "/")
        configure_args = []
        configure_args.append(f"--with-ohos-ndk={sdk_path}")
        configure_args.append("--with-ohos-target=aarch64-linux-ohos")
        configure_args.append("--target=aarch64-linux-ohos")
        configure_args.append("--enable-application=mobile/android")
        configure_args.append("--enable-readline=no")
        configure_args.append("--disable-shared-js")
        configure_args.append("--disable-tests")
        configure_args.append("--disable-gcgenerational")
        configure_args.append("--disable-exact-rooting")
        configure_args.append("--disable-root-analysis")
        configure_args.append("-enable-gcincremental")
        configure_args.append("--disable-gczeal")
        configure_args.append("--without-intl-api")
        configure_args.append("--disable-threadsafe")
        if self.settings.build_type == "Release":
            configure_args.append("--enable-strip")
            configure_args.append("--enable-install-strip")
            configure_args.append("--disable-debug")
            configure_args.append("--enable-debug-symbols=no")
            
        Path(self.folders.base_build+"/js/src/configure").touch()
        autotools.configure(build_script_folder="js/src", args=configure_args)
        autotools.make()

    def package(self):
        copy(self, "LICENSE", self.source_folder, os.path.join(self.package_folder, "licenses"))
        autotools = Autotools(self)
        autotools.install()

    def package_info(self):    
        self.cpp_info.set_property("cmake_find_mode", "both")
        self.cpp_info.set_property("cmake_file_name", "spidermonkey")
        self.cpp_info.set_property("cmake_target_name", "spidermonkey")
        self.cpp_info.set_property("pkg_config_name", "spidermonkey")
        self.cpp_info.libs = ["js_static"]

        # TODO: to remove in conan v2
        self.cpp_info.names["cmake_find_package"] = "spidermonkey"
        self.cpp_info.names["cmake_find_package_multi"] = "spidermonkey"
